package org.chen.wordwave.act;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.hjq.toast.ToastParams;
import com.hjq.toast.Toaster;
import com.hjq.toast.style.CustomToastStyle;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.base.BaseActivity;
import org.chen.wordwave.bean.UpdateUserInfo;
import org.chen.wordwave.tools.email.EmailUtil;
import org.chen.wordwave.tools.md5.MD5Utils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UpdatePassWord extends BaseActivity {
    private ApiService apiService;
    private EditText etEmail;
    private TextView tv_title;
    private EditText etCode, etNewPwd, etConfirmPwd;
    private Button btnSendResetCode, btnResetPwd;
    private String firstEmail;
    private String secondEmail;
    private static final int GET_MESSAGE_CODE = 1;
    private int nowSecond = 60;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == GET_MESSAGE_CODE) {
                if (nowSecond != 0) {
                    btnSendResetCode.setEnabled(false);
                    btnSendResetCode.setText(nowSecond + "s");
                    nowSecond--;
                    handler.sendEmptyMessageDelayed(GET_MESSAGE_CODE, 1000);
                } else {
                    btnSendResetCode.setEnabled(true);
                    btnSendResetCode.setText(R.string.again);
                    nowSecond = 60;
                }
            }
        }
    };
    private ToastParams toastParams = new ToastParams();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        apiService = ApiClient.getClient(this).create(ApiService.class);
    }

    @Override
    public Integer getLayoutResId() {
        return R.layout.update_pws_password_act;
    }

    @Override
    public void init() {
        etEmail = findViewById(R.id.et_email);
        tv_title = findViewById(R.id.tv_title);
        tv_title.setText(R.string.update_pws);
        etCode = findViewById(R.id.et_code);
        etNewPwd = findViewById(R.id.et_new_pwd);
        etConfirmPwd = findViewById(R.id.et_confirm_pwd);
        btnSendResetCode = findViewById(R.id.btn_send_reset_code);
        btnResetPwd = findViewById(R.id.btn_reset_pwd);

        btnSendResetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                firstEmail = etEmail.getText().toString().trim();
                if (TextUtils.isEmpty(firstEmail)) {
                    Toaster.show(getString(R.string.pleass_enter));
                } else {
                    handler.sendEmptyMessage(GET_MESSAGE_CODE);
                    EmailUtil.sendResetPasswordCode(UpdatePassWord.this, firstEmail);
                }
            }
        });

        btnResetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                secondEmail = etEmail.getText().toString().trim();
                String code = etCode.getText().toString().trim();
                String newPassword = etNewPwd.getText().toString().trim();
                String confirmPassword = etConfirmPwd.getText().toString().trim();

                if (TextUtils.isEmpty(code)) {
                    Toaster.show(getString(R.string.PleaseEnterTheVerificationCode));
                    return;
                }

                if (TextUtils.isEmpty(newPassword) || TextUtils.isEmpty(confirmPassword)) {
                    Toaster.show(getString(R.string.please_enter_A_new_password));
                    return;
                }

                if (!newPassword.equals(confirmPassword)) {
                    Toaster.show(getString(R.string.ThePasswordsEnteredTwiceAreInconsistent));
                    return;
                }

                String generatedCode = EmailUtil.getCode();
                if (!code.equals(generatedCode)) {
                    Toaster.show(getString(R.string.VerificationCodeError));
                    return;
                }

                if (etEmail.getText().toString().trim().isEmpty()){
                    Toaster.show(getString(R.string.email_empty));
                    return;
                }

                if (!secondEmail.equals(firstEmail)) {
                    Toaster.show(getString(R.string.VerificationEmailError));
                    return;
                }

                UpdateUserInfo updatePassWord = new UpdateUserInfo();
                updatePassWord.setEmail(etEmail.getText().toString().trim());
                updatePassWord.setPws(MD5Utils.MD5Encode(newPassword,null));
                apiService.updateUserPws(updatePassWord).enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().equals("200")){
                                toastParams.style = new CustomToastStyle(R.layout.success);
                                toastParams.text = getString(R.string.password_update_successful);
                                Toaster.show(toastParams);
                                Intent intent = new Intent(UpdatePassWord.this, Login.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                                finish();
                            }else {
                                toastParams.style = new CustomToastStyle(R.layout.error);
                                toastParams.text = getString(R.string.PasswordUpdateFailedPleaseTryAgain);
                                Toaster.show(toastParams);
                            }
                        } else {
                            toastParams.style = new CustomToastStyle(R.layout.error);
                            toastParams.text = getString(R.string.PasswordUpdateFailedPleaseTryAgain);
                            Toaster.show(toastParams);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                        toastParams.style = new CustomToastStyle(R.layout.error);
                        toastParams.text = getString(R.string.network_error);
                        Toaster.show(toastParams);
                    }
                });
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(GET_MESSAGE_CODE);
    }
}
